<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="房屋名" prop="nameZhCn">
        <el-input
          v-model="queryParams.nameZhCn"
          placeholder="请输入房屋名"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="户型" prop="houseType">
        <el-select
          v-model="queryParams.houseType"
          placeholder="请选择户型"
          clearable
          class="!w-240px"
        >
          <el-option v-for="dict in dictList" :key="dict.id" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="项目类型" prop="projectType">
        <el-select
          v-model="queryParams.projectType"
          placeholder="请选择项目类型"
          clearable
          class="!w-240px"
        >
          <el-option v-for="dict in dictList2" :key="dict.id" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="销售方式" prop="salesMethodZhCn">
        <el-input
          v-model="queryParams.salesMethodZhCn"
          placeholder="请输入销售方式中文名"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="市区" prop="provinceId">
        <el-cascader
          v-model="queryParams.provinceId"
          :options="openedCityTree"
          :props="{ expandTrigger: 'hover', checkStrictly: true, label: 'name', value: 'id' }" />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['business:ready-house:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['business:ready-house:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <el-button
          type="warning"
          plain
          @click="handleImport"
          v-hasPermi="['business:apartment:export']"
        >
          <Icon icon="ep:upload" /> 现房信息导入
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="房名" align="center" prop="nameZhCn">
        <template #default="{row}">
          <p>{{row.nameZhCn}}</p>
          <p>{{row.nameEnUs}}</p>
        </template>
      </el-table-column>
      <el-table-column label="展示图" align="center" prop="showImages">
        <template #default="{row}">
          <el-row type="flex" class="row-bg" justify="space-between">
            <el-col :span="8" v-for="(image, i) in row.showImages" :key="i">
              <el-image
                class="h-50px w-50px"
                lazy
                :src="image"
                :preview-src-list="[image]"
                preview-teleported
                fit="cover"
              />
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column label="导流率" align="center" prop="dll">
        <template #default="{row}">
          <p>浏览量：{{ row.lookCount }}</p>
          <p>关注数：{{ row.followCount }}</p>
          <p>咨询数：{{ row.consultCount }}</p>
        </template>
      </el-table-column>
<!--      <el-table-column label="房屋图片（多个逗号分隔）" align="center" prop="showImages" />
      <el-table-column label="房屋视频（多个逗号分隔）" align="center" prop="showVideos" />
      <el-table-column label="房屋户型图（多个逗号分隔）" align="center" prop="showImagesHouseType" />-->
      <el-table-column label="价格" align="center" prop="priceMin">
        <template #default="{row}">
          <p>${{row.priceMin}} 起</p>
        </template>
      </el-table-column>
<!--      <el-table-column label="项目类型" align="center" prop="projectType">
        <template #default="{row}">
          <el-tag type="warning" v-if="row.projectType === 0">公寓</el-tag>
          <el-tag v-else-if="row.projectType === 1">新房</el-tag>
          <el-tag type="success" v-else>二手</el-tag>
        </template>
      </el-table-column>-->
      <el-table-column label="详细信息" min-width="110" align="left" prop="houseArea">
        <template #default="{row}">
          <p>项目类型：{{dictList2.find(item => item.value == row.projectType)?.label}}</p>
          <p>户型：{{dictList.find(item => item.value == row.houseType)?.label}}</p>
          <p>销售方式：{{row.salesMethodZhCn}} ({{row.salesMethodEnUs}})</p>
          <p>面积：{{row.houseArea}} ㎡</p>
          <p>位置：{{row.pointDetail}}</p>
        </template>
      </el-table-column>
      <el-table-column label="标签" align="left" prop="tagsZhCn">
        <template #default="{row}">
          <el-row type="flex" class="row-bg" justify="space-between">
            <el-col :span="(24 / row.tagsZhCn.length > 2 ? 12 : 24)" v-for="(tag, i) in row.tagsZhCn" :key="i"><el-tag>{{tag}}</el-tag></el-col>
          </el-row>
          <el-row type="flex" class="row-bg" justify="space-between">
            <el-col :span="(24 / row.tagsEnUs.length > 2 ? 12 : 24)" v-for="(tag, i) in row.tagsEnUs" :key="i"><el-tag>{{tag}}</el-tag></el-col>
          </el-row>
        </template>
      </el-table-column>
<!--      <el-table-column label="省市区" align="center" prop="provinceId">
        <template #default="{row}">
          <p>{{row.provinceId}}</p>
        </template>
      </el-table-column>-->
      <el-table-column label="状态" key="isShow">
        <template #default="scope">
          <el-switch
            v-model="scope.row.isShow"
            :active-value="true"
            :inactive-value="false"
            @change="handleStatusChange(scope.row.id, scope.row.isShow)"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['business:ready-house:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['business:ready-house:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <Dialog v-model="dialogVisible" title="现房导入" width="400">
    <el-upload
      ref="uploadRef"
      v-model:file-list="fileList"
      :action="importUrl"
      :auto-upload="false"
      :disabled="formLoading"
      :headers="uploadHeaders"
      :limit="1"
      :on-error="submitFormError"
      :on-exceed="handleExceed"
      :on-success="submitFormSuccess"
      accept=".xlsx, .xls"
      drag
    >
      <Icon icon="ep:upload" />
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <template #tip>
        <div class="el-upload__tip text-center">
          <span>仅允许导入 xls、xlsx 格式文件。</span>
          <a href="https://silushiye-1330523338.cos.ap-guangzhou.myqcloud.com/silushiye-1330523338/20251030/ready_house_template_1761824790045.xlsx" download="现房模板.xlsx">
            <el-button size="small" type="text" plain >下载模板</el-button>
          </a>
        </div>
      </template>
    </el-upload>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>

  <!-- 表单弹窗：添加/修改 -->
  <ReadyHouseForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { ReadyHouseApi, ReadyHouseVO } from '@/api/business/readyhouse'
import ReadyHouseForm from './ReadyHouseForm.vue'
import {OpenedCityApi} from "@/api/business/openedcity";
import {handleTree} from "@/utils/tree";
import {BizDictTypeApi} from "@/api/business/dicttype";
import {getAccessToken, getTenantId} from "@/utils/auth";
import * as UserApi from "@/api/system/user";
import {ApartmentApi} from "@/api/business/apartment";

/** 现房 列表 */
defineOptions({ name: 'ReadyHouse' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const handleStatusChange = async (id:number, isShow0:boolean) => {
  try {
    // 发起修改状态
    await ReadyHouseApi.updateReadyHouseStatus({id: id, isShow: isShow0})
    // 刷新列表
    await getList()
  } catch {
  }
}


const loading = ref(true) // 列表的加载中
const list = ref<ReadyHouseVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  nameZhCn: undefined,
  houseType: undefined,
  priceMin: undefined,
  priceMax: undefined,
  tagsZhCn: undefined,
  tagsEnUs: undefined,
  projectType: undefined,
  salesMethodZhCn: undefined,
  salesMethodEnUs: undefined,
  houseArea: undefined,
  contentZhCn: undefined,
  contentEnUs: undefined,
  provinceId: undefined,
  cityId: undefined,
  countyId: undefined,
  point: undefined,
  pointDetail: undefined,
  createTime: [],
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

const dictList = ref() // 弹窗的是否展示
const getDictDataList = async (id: number) => {
  dictList.value = await BizDictTypeApi.getBizDictDataByTypeId(id)
}

const dictList2 = ref() // 弹窗的是否展示
const getDictDataList2 = async (id: number) => {
  dictList2.value = await BizDictTypeApi.getBizDictDataByTypeId(id)
}

const openedCityTree = ref() // 树形结构

/** 获得已开通城市树 */
const getOpenedCityTree = async () => {
  openedCityTree.value = []
  const data = await OpenedCityApi.getOpenedCityList()
  openedCityTree.value = handleTree(data, 'id', 'parentId')
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ReadyHouseApi.getReadyHousePage(queryParams)
    await getDictDataList(1)
    await getDictDataList2(2)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await ReadyHouseApi.deleteReadyHouse(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await ReadyHouseApi.exportReadyHouse(queryParams)
    download.excel(data, '现房.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}




const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中
const uploadRef = ref()
const importUrl =
  import.meta.env.VITE_BASE_URL + import.meta.env.VITE_API_URL + '/business/ready-house/import-excel'
const uploadHeaders = ref() // 上传 Header 头
const fileList = ref([]) // 文件列表
const handleImport = () => {
  dialogVisible.value = true
  fileList.value = []
}

/** 提交表单 */
const submitForm = async () => {
  if (fileList.value.length == 0) {
    message.error('请上传文件')
    return
  }
  // 提交请求
  uploadHeaders.value = {
    Authorization: 'Bearer ' + getAccessToken(),
    'tenant-id': getTenantId()
  }
  formLoading.value = true
  uploadRef.value!.submit()
}

/** 文件上传成功 */
const emits = defineEmits(['success'])
const submitFormSuccess = (response: any) => {
  if (response.code !== 0) {
    message.error(response.msg)
    formLoading.value = false
    return
  }
  message.alert('上传成功')
  formLoading.value = false
  dialogVisible.value = false
  fileList.value = []
  getList()
  // 发送操作成功的事件
  emits('success')
}

/** 上传错误提示 */
const submitFormError = (): void => {
  message.error('上传失败，请您重新上传！')
  formLoading.value = false
}
/** 文件数超出提示 */
const handleExceed = (): void => {
  message.error('最多只能上传一个文件！')
}



/** 初始化 **/
onMounted(() => {
  getList()
  getOpenedCityTree()
})
</script>
